<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 21:26
 */

namespace app\common\lib;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Regions\EndpointConfig;
use app\common\cachemodel\AppConfig;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\service\CacheZyhs;
use think\Cache;

/**
 * 阿利大于短信相关
 * Class Alidayu
 * @package app\common\lib
 */
class Alidayu
{
    const LOG_TPL = "alidayu:";
    /**
     * 静态变量保存全局的实例
     * @var null
     */
    private static $_instance = null;

    /**
     * 私有的构造方法
     */
    private function __construct()
    {
    }

    private static $loaded = false;
    public static function load(){
        if(self::$loaded) {
            return;
        }
        EndpointConfig::load();
        self::$loaded = true;
    }

    /**
     * 静态方法 单例模式统一入口
     */
    public static function getInstance()
    {
        if (is_null(self::$_instance))
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * 发送短信接口
     * 文档地址 https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.lX0Upj
     * @param int $mobile 手机号
     * @param $params string 验证码
     * @param $code int 短信模版id
     * @param int $areaCode 手机区号
     * @return mixed    code = OK 表示完成
     */
    public function sendSms($mobile, $params, $code, $areaCode = 86)
    {
        require_once VENDOR_PATH . '/aliyunsms/vendor/autoload.php';

        $alidayu = (new AppConfig())->configInfo('alidayu');

        $sendMobile = $areaCode === 86 ? $mobile : $areaCode . $mobile;
        //获取短信配置
        $appkey = $alidayu['appkey'];
        $secretkey = $alidayu['secretkey'];
        $name = $alidayu['name'];

        Config::load();
        $templateParam = ['code' => $params];
        $product = "Dysmsapi";
        $domain = "dysmsapi.aliyuncs.com";
        $region = "cn-hangzhou";
        try
        {
            $profile = DefaultProfile::getProfile($region, $appkey, $secretkey);
            DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
            $acsClient = new DefaultAcsClient($profile);

            $request = new SendSmsRequest();
            $request->setPhoneNumbers($sendMobile);
            $request->setSignName($name);
            $request->setTemplateCode($code);
            if ($templateParam)
            {
                $request->setTemplateParam(json_encode($templateParam));
            }
            $acsResponse = $acsClient->getAcsResponse($request);

        }
        catch (\Exception $e)
        {
            return false;
        }
        // 发送成功
        if ($acsResponse->Code == 'OK')
        {
            $cacheMobiel = $areaCode === 86 ? $mobile : $areaCode . '-' . $mobile;
            // 设置验证码 并设置失效时间600/s  10分钟  存入缓存redis中
            Cache::set($cacheMobiel, $params, $alidayu['time']);
            return true;
        }
//        else
//        {
//            Log::write(self::LOG_TPL. var_export($acsResponse,true));
//        }
        return false;
    }

    /**
     * 发送短信接口
     * 文档地址 https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.lX0Upj
     * @param int $mobile 手机号
     * @param $params string 验证码
     * @param $code int 短信模版id
     * @param int $areaCode 手机区号
     * @param string $codeType login => 登录 bind => 绑定 logout => 注销  astrologer=>占星师验证码
     * @return mixed    code = OK 表示完成
     * @throws \Exception
     */
    public function sendSms1($mobile, $params, $code, $areaCode = 86, string $codeType = '')
    {
        require_once VENDOR_PATH . '/aliyunsms/vendor/autoload.php';

        $alidayu = (new AppConfig())->configInfo('alidayu');

        $sendMobile = $areaCode === 86 ? $mobile : $areaCode . $mobile;
        //获取短信配置
        $appkey = $alidayu['appkey'];
        $secretkey = $alidayu['secretkey'];
        $name = $alidayu['name'];

        Config::load();
        $templateParam = ['code' => $params];
        $product = "Dysmsapi";
        $domain = "dysmsapi.aliyuncs.com";
        $region = "cn-hangzhou";
        try
        {
            $profile = DefaultProfile::getProfile($region, $appkey, $secretkey);
            DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
            $acsClient = new DefaultAcsClient($profile);

            $request = new SendSmsRequest();
            $request->setPhoneNumbers($sendMobile);
            $request->setSignName($name);
            $request->setTemplateCode($code);
            if ($templateParam)
            {
                $request->setTemplateParam(json_encode($templateParam));
            }
            $acsResponse = $acsClient->getAcsResponse($request);

        }
        catch (\Exception $e)
        {
            return false;
        }
        // 发送成功
        if ($acsResponse->Code == 'OK')
        {
            $cacheMobiel = $areaCode === 86 ? $mobile : $areaCode . '-' . $mobile;

            $cacheMobiel = $codeType . ':' . $cacheMobiel;
            // 设置验证码 并设置失效时间600/s  10分钟  存入缓存redis中
            Cache::set($cacheMobiel, $params, $alidayu['time']);
            return true;
        }
//        else
//        {
//            Log::write(self::LOG_TPL. var_export($acsResponse,true));
//        }
        return false;
    }

    /**
     * 发送 美国 短信接口
     * 文档地址 https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.lX0Upj
     * @param int $mobile 手机号
     * @param $smsCode string 验证码
     * @param $smsType string 短信类型
     * @return mixed    code = OK 表示完成
     */
    public function sendSmsUSA($mobile, $smsCode, $smsType)
    {
        if (in_array($smsType, ['logout_code', 'abroad_logout_code'], true))
        {   // 注销
            $message = "[ZHUNLE]You are deregistering your account. If it is not performed by yourself, please contact customer service. The code is {$smsCode}.";
        } elseif (in_array($smsType, ['login_code', 'abroad_login_code'], true))
        {   // 登录 ｜ 绑定      【ZHUNLE】您的验证码为:${code}，验证码有效期为10分钟，请勿透露给他人。
            $message = "[ZHUNLE]Your verification code is: {$smsCode}, the verification code is valid for 10 minutes, do not disclose to others.";
        } else
        {
            return false;
        }

        $alidayu = (new AppConfig())->configInfo('alidayu');
        //获取短信配置
        $appkey = $alidayu['appkey'];
        $secretkey = $alidayu['secretkey'];

        AlibabaCloud::accessKeyClient($appkey, $secretkey)->regionId('cn-beijing')->asDefaultClient();
        try
        {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendMessageToGlobe')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'To' => "1{$mobile}",//接收短信号码。号码格式为：国际区号+号码  美国 区号 1
                        'From' => "18667851502",//发送方标识。支持SenderID的发送，只允许数字+字母，含有字母标识最长11位，纯数字标识支持15位
                        'Message' => $message,//短信的完整内容
                        'Type' => "OTP",//短信类型
                    ],
                ])
                ->request();
            $resData = $result->toArray();
        }
        catch (ClientException $e)
        {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        catch (ServerException $e)
        {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        // 发送成功
        if ($resData['Code'] === 'OK')
        {
            $cacheMobiel = '1-' . $mobile;
            // 设置验证码 并设置失效时间600/s  10分钟  存入缓存redis中
            Cache::set($cacheMobiel, $smsCode, $alidayu['time']);
            return true;
        }

        return false;
    }

    /**
     * 根据手机号码查询验证码是否正常
     * @param int $phone
     * @param int $areaCode
     * @return boolean
     */
    public function checkSmsIdentify($phone = 0, $areaCode = 86)
    {
        if (!$phone) return false;
        $cacheKey = $areaCode === 86 ? $phone : $areaCode . '-' . $phone;
        return Cache::get($cacheKey);
    }

    /**
     * 根据手机号码查询验证码是否正常
     * @param int $phone
     * @param int $areaCode
     * @param string $codeType login => 登录 bind => 绑定 logout => 注销  astrologer=>占星师验证码
     * @return boolean
     */
    public function checkSmsIdentify1($phone = 0, $areaCode = 86, string $codeType = '')
    {
        if (!$phone) return false;
        $cacheKey = $areaCode === 86 ? $phone : $areaCode . '-' . $phone;
        $cacheKey = $codeType . ':' . $cacheKey;
        return Cache::get($cacheKey);
    }

    /**
     * 发送短信接口   ------------------- 准有好事 -------------------
     * 文档地址 https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.lX0Upj
     * @param int $mobile 手机号
     * @param $params string 验证码
     * @param $code int 短信模版id
     * @param int $areaCode 手机区号
     * @param string $codeType login => 登录 bind => 绑定 logout => 注销  astr_team:login_code => 占星师团队
     * @return mixed    code = OK 表示完成
     * @throws \Exception
     */
    public function sendSmsZyhs($mobile, $params, $code, $areaCode = 86, string $codeType = '')
    {
        require_once VENDOR_PATH . '/aliyunsms/vendor/autoload.php';

        $alidayu = (new ZyhsConfig())->configInfo('alidayu');

        $sendMobile = $areaCode === 86 ? $mobile : $areaCode . $mobile;
        //获取短信配置
        $appkey = $alidayu['appkey'];
        $secretkey = $alidayu['secretkey'];
        $name = $alidayu['name'];

        Config::load();
        $templateParam = ['code' => $params];
        $product = "Dysmsapi";
        $domain = "dysmsapi.aliyuncs.com";
        $region = "cn-hangzhou";
        try
        {
            $profile = DefaultProfile::getProfile($region, $appkey, $secretkey);
            DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
            $acsClient = new DefaultAcsClient($profile);

            $request = new SendSmsRequest();
            $request->setPhoneNumbers($sendMobile);
            $request->setSignName($name);
            $request->setTemplateCode($code);
            if ($templateParam)
            {
                $request->setTemplateParam(json_encode($templateParam));
            }
            $acsResponse = $acsClient->getAcsResponse($request);

        }
        catch (\Exception $e)
        {
            return false;
        }
        // 发送成功
        if ($acsResponse->Code == 'OK')
        {
            $cacheMobiel = $areaCode === 86 ? $mobile : $areaCode . '-' . $mobile;

            $cacheMobiel = $codeType . ':' . $cacheMobiel;
            // 设置验证码 并设置失效时间600/s  10分钟  存入缓存redis中
            CacheZyhs::set($cacheMobiel, $params, $alidayu['time']);
            return true;
        }

        return false;
    }

    /**
     * 根据手机号码查询验证码是否正常  ------------------- 准有好事 -------------------
     * @param string $phone
     * @param int $areaCode
     * @param string $codeType login => 登录 bind => 绑定 logout => 注销  astrologer=>占星师验证码
     * @return boolean
     * @throws \Exception
     */
    public function checkSmsIdentifyZyhs($phone = '', $areaCode = 86, string $codeType = '')
    {
        if (!$phone) return false;
        $cacheKey = $areaCode === 86 ? $phone : $areaCode . '-' . $phone;
        $cacheKey = $codeType . ':' . $cacheKey;
        return CacheZyhs::get($cacheKey);
    }


    /**
     * 准有好事 发送 短信消息通知
     * @param int $areaCode
     * @param $mobile
     * @param $smsTpid
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function zyhsMsgSmsSend(int $areaCode = 86, $mobile, $smsTpid, $params)
    {
        require_once VENDOR_PATH . '/aliyunsms/vendor/autoload.php';

        $alidayu = (new ZyhsConfig())->configInfo('alidayu');

        $sendMobile = $areaCode === 86 ? $mobile : $areaCode . $mobile;
        //获取短信配置
        $appkey = $alidayu['appkey'];
        $secretkey = $alidayu['secretkey'];
        $name = '准有好事';

        defined('ENABLE_HTTP_PROXY') or define('ENABLE_HTTP_PROXY', FALSE);
        defined('HTTP_PROXY_IP') or define('HTTP_PROXY_IP', '127.0.0.1');
        defined('HTTP_PROXY_PORT') or define('HTTP_PROXY_PORT', '8888');

        self::load();
        $product = "Dysmsapi";
        $domain = "dysmsapi.aliyuncs.com";
        $region = "cn-hangzhou";
        try
        {
            $profile = DefaultProfile::getProfile($region, $appkey, $secretkey);
            DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
            $acsClient = new DefaultAcsClient($profile);

            $request = new SendSmsRequest();
            $request->setPhoneNumbers($sendMobile);
            $request->setSignName($name);
            $request->setTemplateCode($smsTpid);
            if ($params)
            {
                $request->setTemplateParam(json_encode($params));
            }
            $acsResponse = $acsClient->getAcsResponse($request);

        }
        catch (\Exception $e)
        {
            return false;
        }
        // 发送成功
        if ($acsResponse->Code == 'OK')
        {
            return true;
        }

        return false;
    }
}
